import path from 'path';
import fs from 'fs';
import electron, { ipcRenderer } from 'electron';
import { mkdirSync, isDev } from '../util';
import { version } from '../../package.json';
import appinfo from '../appinfo';

export const loger = console;

const app = electron.app || electron.remote.app;
const configfile = 'app.json';
const appPath = process.env.INIT_CWD || path.dirname(app.getPath('exe'));

/**
 * appdata目录
 */
const getAppData = () => {
  try {
    return path.join(app.getPath('appData'), appinfo.name);
  } catch (error) {
    return path.join(appPath, 'data');
  }
};

/**
 * temp临时目录
 */
const getTemp = () => {
  try {
    return app.getPath('temp');
  } catch (error) {
    return path.join(appPath, 'temp');
  }
};

/**
 * 获取主版本号
 */
const getMajorVersion = () => {
  try {
    return `${version.split('.')[0]}.0.0`;
  } catch (error) {
    return '999.999.999';
  }
};

/**
 * 获取我的文档目录
 */
const getDocumentDir = () => {
  try {
    return app.getPath('documents');
  } catch (error) {
    //
  }
};
/**
 * 常用目录
 */
const dirs = {
  appPath,
  appData: getAppData(),
  temp: getTemp(),
};
const userDataConfig1 = path.join(dirs.appData, configfile);
const userDataConfig2 = path.join(dirs.appPath, configfile);
let privatedataDir = getDocumentDir();
/**
 * 读取配置
 * @param {*} file
 */
const readJson = (file) => {
  try {
    if (fs.existsSync(file)) {
      const obj = JSON.parse(fs.readFileSync(file, 'utf8'));
      privatedataDir = obj.dataDir || privatedataDir;
      return obj;
    }
  } catch (error) {
    //
  }
  return {};
};

let prjCfg;
switch (appinfo.prj) {
  case 'yuexuewangyue':
    prjCfg =
      isDev || __dev
        ? {
            urlApp: 'http://192.168.1.98/wyclint/#/login',
            urlDownload: 'http://192.168.1.100:91/cdn/download/yuexuewangyue/',
          }
        : {
            urlApp: 'https://wangyue.henanyuexue.com/client/',
            urlDownload: 'https://wangyue.henanyuexue.com/static/download/',
          };
    break;
  case 'hnszjc':
    prjCfg =
      isDev || __dev
        ? {
            urlApp: 'http://192.168.1.98/hnszjc-pc/',
            urlDownload: 'http://192.168.1.100:91/cdn/download/hnszjc/',
          }
        : { urlApp: 'https://www.hnszjc.com/app/pc/v1/index.html', urlDownload: 'http://cdn.henanyuexue.com/static/download/' };
    break;
  case 'szjcyyy':
    prjCfg =
      isDev || __dev
        ? {
            urlApp: 'http://192.168.1.98/main/',
            urlDownload: 'http://192.168.1.100:91/cdn/download/',
          }
        : { urlApp: 'https://szjcyyy.com/main/', urlDownload: 'https://szjcyyy.com/static/download/' };
    break;
  default:
    prjCfg = {};
    break;
}

// WARNING! 网址已"/"结束
const cfg = {
  ...prjCfg,
  ...readJson(userDataConfig1),
  ...readJson(userDataConfig2),
  dirs,
  name: appinfo.name,
  version,
  get dataDir() {
    return path.join(privatedataDir, appinfo.name);
  },
};

if (!cfg.urlDownload.endsWith('/')) cfg.urlDownload = `${cfg.urlDownload}/`;
cfg.urlDownload = `${cfg.urlDownload}${getMajorVersion()}/`;
/**
 * 保存配置
 */
const save = () => {
  try {
    mkdirSync(path.dirname(userDataConfig1));
    //eslint-disable-next-line
    const { name, version, dirs, urlApp, urlDownload, save, getDataDir, dataDir, ...cfgData } = cfg;
    const content = JSON.stringify({ ...readJson(userDataConfig1), dataDir: privatedataDir, ...cfgData }, null, 2);
    fs.writeFileSync(userDataConfig1, content);
  } catch (error) {
    //
  }
};

/**
 * 获取应用数据目录
 */
const getDataDir = ({ promptToSelect = true, title } = {}) => {
  return new Promise((resolve, reject) => {
    if (privatedataDir && fs.existsSync(privatedataDir)) {
      resolve(cfg.dataDir);
      return;
    }
    if (!promptToSelect) {
      reject('数据保存位置未设置');
      return;
    }
    ipcRenderer.send('showOpenDialog', {
      title: title || `设置数据保存位置【应用会创建“${appinfo.name}”文件夹】`,
      properties: ['openDirectory'],
    });
    ipcRenderer.once('showOpenDialog', (e, [filePath] = []) => {
      if (filePath && fs.existsSync(filePath)) {
        privatedataDir = filePath;
        cfg.save();
        resolve(cfg.dataDir);
      } else {
        reject('数据保存位置未设置');
      }
    });
  });
};

cfg.save = save;
cfg.getDataDir = getDataDir;
export default cfg;
